package mango.web.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

public class Property {
	public static Map<String, Property> propertyMap = new HashMap<String, Property>();

	public String file = "";

	public static Property get(String key) {
		Property property = Property.propertyMap.get(key);
		if (property == null) {
			property = new Property();
			property.file = key;
			property.loadFile();
			Property.propertyMap.put(key, property);
		}
		return property;
	}

	public Map<String, String> map;

	public Map<String, String> loadFile() {
		this.map = new HashMap<String, String>();
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(this.file);
			br = new BufferedReader(fr);
			String line;
			while ((line = br.readLine()) != null) {
				if ("".equals(line.trim()) || line.startsWith("#")) continue;
				String[] arr = line.split("=", 2);
				this.map.put(arr[0], arr[1]);
			}
			br.close();
			fr.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return this.map;
	}

	public Map<String, String> saveFile() {
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(this.file);
			bw = new BufferedWriter(fw);
			for (String key : this.map.keySet()) {
				bw.write(key + "=" + this.map.get(key) + "\n");
			}
			bw.close();
			fw.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return this.map;
	}
}
